package sourismobile.server.core;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

import java.io.*;


public class BluetoothServer implements Runnable {

	UUID uuid = null;
	String name = "SourisMobileServer";
	StreamConnectionNotifier notifier;
	DataInputStream in;
	DataOutputStream out;

	ServiceConnector serviceConnector;

	boolean flag = true;

	public void setFlag(boolean value) {
		this.flag = value;
	}

	public void run() {
		System.out.println("Entering in BluetoothServer.");
		String url = "btspp://localhost:" + "86b4d249fb8844d6a756ec265dd1f6a4" +
		";name=" + name;
		System.out.println(url);

		try {
			notifier = (StreamConnectionNotifier) Connector.open(url);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}


		System.out.println("Waiting for connection...\n");

		try {
			StreamConnection connection = notifier.acceptAndOpen();
			System.out.println("Connected !");

			in  = new DataInputStream ( connection.openInputStream()  );
			out = new DataOutputStream( connection.openOutputStream() );

			System.out.println("Attende du mode");
			while (flag) {

				if(in.available()!=0) {
					int moduleCode = in.readInt();
					System.out.println("\n- Mode selected - " + moduleCode);

					if (moduleCode > 0 && moduleCode < 10) {
						serviceConnector = new ServiceConnector(out, in, moduleCode, this);
						serviceConnector.run();
						System.out.println("Module Ending !");
					}
					else if (moduleCode == 0) {
						in.close();
						out.close();
						connection.close();
						notifier.close();
						return;
						}
				}
				else {System.out.print("-");}
				Thread.sleep(100);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

	}

}
